<?php

namespace app\api\controller;

use app\admin\model\manystore\Shop;
use app\common\controller\Api;
use app\common\model\Commission;
use think\Db;
use think\Validate;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 首页
     *
     */
    public function index()
    {
        $this->success('请求成功');
    }

    public function mine()
    {
        $userModel = new \app\common\model\User();
        $usernum = $userModel->where(['p_id' => $this->auth->id])->count('id');

        $commissionModel = new Commission();
        $commissionmony =  $commissionModel->where(['user_id' => $this->auth->id])->sum('money');
        $this->success('请求成功',[
            'usernum' => $usernum,
            'commissionmony' => $commissionmony
        ]);
    }

    //注册用户
    public function register()
    {
        $username = $this->request->post('username');
        $mobile = $this->request->post('mobile');
        $avatar = $this->request->post('avatar');
        $p_id = $this->request->post('p_id');
        $username = $mobile;
//        if (!$username) {
//            $this->error(__('Invalid parameters'));
//        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $shop = Shop::get(['user_id' => $p_id]);
        if(!$shop) $this->error('未申请渠道');
        $user_id = $this->auth->register($username, 123456, '', $mobile, ['avatar' => $avatar, 'p_id' => $p_id, 'shop_id' => $shop->id]);
        if ($user_id) {
            $this->success(__('Sign up successful'),['user_id' => $user_id]);
        } else {
            $this->error($this->auth->getError());
        }
    }

    //佣金
    public function commission()
    {
        $p_id = $this->request->post('p_id');
        $user_id = $this->request->post('user_id');
        $money = $this->request->post('money');
        $no = $this->request->post('no');
        $time = $this->request->post('time');
        $type = $this->request->post('type'); //类型：

        $shop = Shop::get(['user_id' => $p_id]);
        if(!$shop) $this->error('未申请渠道');

        Db:name('commission')->create([
            'p_id' =>$p_id,
            'user_id' =>$user_id,
            'money' => $money,
            'no' => $no,
            'type' => $type,
            'create_time' => $time
        ]);

        \app\common\model\User::money($money,$user_id,'佣金');

        $this->success(__('Sign up successful'));
    }
}
